<template>
  <div class="app-container">
    <!-- 返回按钮 -->
    <div class="header-section">
      <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="名称" prop="couponName" v-if="!couponId">
          <el-input
            v-model="queryParams.couponName"
            placeholder="请输入优惠券名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="会员名称" prop="memberName">
          <el-input
            v-model="queryParams.memberName"
            placeholder="请输入会员名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="领取时间" prop="receiveTime">
          <el-date-picker
            v-model="queryParams.receiveTime"
            type="datetime"
            placeholder="选择领取时间"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="获取方式" prop="obtainMethod">
          <el-select
            v-model="queryParams.obtainMethod"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="免费获取" value="免费获取" />
            <el-option label="活动获取" value="活动获取" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="couponStatus">
          <el-select
            v-model="queryParams.couponStatus"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="已领取" value="已领取" />
            <el-option label="已使用" value="已使用" />
            <el-option label="已过期" value="已过期" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="couponRecordList" style="width: 100%">
      <el-table-column label="会员名称" prop="memberName" align="center" />
      <el-table-column label="优惠券名称" prop="couponName" align="center" />
      <el-table-column label="发布店铺" prop="issuingStore" align="center">
        <template #default="scope">
          <span>{{ scope.row.issuingStore || '平台' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="面额/折扣" prop="amount" align="center">
        <template #default="scope">
          <span>¥{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用门槛" prop="usageThreshold" align="center">
        <template #default="scope">
          <span>{{ scope.row.usageThreshold }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获取方式" prop="obtainMethod" align="center">
        <template #default="scope">
          <el-tag 
            :type="getObtainMethodType(scope.row.obtainMethod)" 
            size="small"
          >
            {{ scope.row.obtainMethod }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠券状态" prop="couponStatus" align="center">
        <template #default="scope">
          <el-tag type="info" size="small">
            {{ scope.row.couponStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠券类型" prop="couponType" align="center">
        <template #default="scope">
          <el-tag type="warning" size="small">
            {{ getCouponTypeText(scope.row.couponType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="品类描述" prop="categoryDesc" align="center">
        <template #default="scope">
          <span>{{ scope.row.categoryDesc || '全品类' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领取时间" prop="receiveTime" align="center">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.receiveTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="CouponRecord">
import { ref, reactive, onMounted, onActivated, watch, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { listCouponReceiveRecord } from '@/api/coupon/couponRecord'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

const loading = ref(true)
const total = ref(0)
const couponRecordList = ref([])
const couponId = ref(route.query.couponId || null)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  couponId: null, // 初始化为null，在onMounted中根据路由参数设置
  couponName: '', // 优惠券名称筛选
  memberName: '',
  obtainMethod: '', // 对应数据库字段 obtain_method
  couponStatus: '', // 对应数据库字段 coupon_status
  receiveTime: '' // 对应数据库字段 receive_time
})

// 获取优惠券领取记录列表
function getList() {
  loading.value = true
  listCouponReceiveRecord(queryParams).then(response => {
    couponRecordList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 返回
function goBack() {
  router.back()
}

// 获取方式类型
function getObtainMethodType(method) {
  const typeMap = {
    '免费获取': 'danger',
    '活动获取': 'warning'
  }
  return typeMap[method] || 'info'
}

// 格式化日期时间
function formatDateTime(dateTime) {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 优惠券类型文本
function getCouponTypeText(type) {
  const typeMap = {
    'CASH': '减免现金',
    'DISCOUNT': '打折'
  }
  return typeMap[type] || type
}

onMounted(() => {
  queryParams.couponId = couponId.value
  getList()
})

// 监听路由参数变化（例如从列表再次点击不同优惠券的领取记录）
watch(
  () => route.query.couponId,
  (newVal) => {
    couponId.value = newVal || null
    queryParams.couponId = couponId.value
    queryParams.pageNum = 1
    getList()
  }
)

// 处理 keep-alive 激活时的刷新
onActivated(() => {
  couponId.value = route.query.couponId || null
  queryParams.couponId = couponId.value
  queryParams.pageNum = 1
  getList()
})
</script>

<style scoped>
.header-section {
  margin-bottom: 20px;
}

.search-section {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-section .el-form-item {
  margin-bottom: 15px;
}

.search-section .el-button {
  margin-left: 10px;
}
</style>
